//201902104030_何琛选
package cn.edu.sdjzu.xg.bysj.controller.basic;

import cn.edu.sdjzu.xg.bysj.domain.ApplicationForSupervisor;
import cn.edu.sdjzu.xg.bysj.service.ApplicationForSupervisorService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import util.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@Slf4j
@WebServlet("/ApplicationForSupervisor1.ctl")
public class ApplicationForSupervisorController extends HttpServlet {
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
            throws ServletException, IOException {
        //设置请求字符编码为UTF-8
        request.setCharacterEncoding("UTF-8");
        //根据request对象，获得代表新增Teacher的JSON字串
        String req_afsToAdd_jsonStr = JSONUtil.getJSON(request);
        JSONObject req_jsonObj = JSON.parseObject(req_afsToAdd_jsonStr);

        JSONArray req_jsonArr = req_jsonObj.getJSONArray("applicationForSupervisor");

        List<ApplicationForSupervisor> req_javaList =
                req_jsonArr.toJavaList(ApplicationForSupervisor.class);

        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            //在数据库表中增加Teacher对象
            ApplicationForSupervisorService.getInstance().add(req_javaList);
            respMessage_jsonObj.put("message", "增加成功");
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            //打印异常栈，方便调试（要用log4j代替）
            log.debug(e.getMessage());
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //打印异常栈，方便调试（要用log4j代替）
            log.debug(e.getMessage());
        }
        //响应respMessage_jsonObj到前端
        response.getWriter().println(respMessage_jsonObj);
    }
}
